package com.cheney.common.mybatisplus.filter;

import com.cheney.common.mybatisplus.context.TenantContextHolder;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;


/**
 * 租户过滤器
 *
 * @author chensi
 */
@Component
@Order(-100)
public class TenantContextHolderFilter extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response,
                                    FilterChain filterChain) throws IOException, ServletException {
        try {
//            LoginUser loginUser = tokenService.getLoginUser(request);
//            //保存token中的租户信息
//            if (loginUser != null) {
//                //保存tenantId
//                TenantContextHolder.setTenant(loginUser.getUser().getUserId() + "");
//                //todo 根据数据权限选择保存tenantGroup还是保存所有
//                List<SysRole> list = loginUser.getUser().getRoles();
//                for (SysRole item : list) {
//                    if (loginUser.getUser().isAdmin() || StrUtil.equals(item.getDataScope(), DATA_SCOPE_ALL)) {
//                        TenantContextHolder.setTenant("all");
//                    }
//                }
//            } else {
//                //没有租户信息，则展示不存在的租户的数据
//                TenantContextHolder.setTenant("-1");
//            }
            filterChain.doFilter(request, response);
        } finally {
            TenantContextHolder.clear();
        }
    }
}
